package ch16 {
	import flash.display.Sprite;
	import flash.events.Event;
	import utils.Point3D;

	/**
	 * 3D字母E，创建 3D 填充
	 * @author jianping.shenjp
	 */
	public class FilledE extends Sprite {

		private var points:Array;
		private var numPoints:uint = 12;
		//焦距
		private var fl:Number = 250;
		//消失点
		private var vpX:Number = stage.stageWidth / 2;
		private var vpY:Number = stage.stageHeight / 2;

		public function FilledE(){
			init();
		}

		private function init():void {
			points = new Array();
			points[0] = new Point3D(-150, -250, 100);
			points[1] = new Point3D(150, -250, 100);
			points[2] = new Point3D(150, -150, 100);
			points[3] = new Point3D(-50, -150, 100);
			points[4] = new Point3D(-50, -50, 100);
			points[5] = new Point3D(50, -50, 100);
			points[6] = new Point3D(50, 50, 100);
			points[7] = new Point3D(-50, 50, 100);
			points[8] = new Point3D(-50, 150, 100);
			points[9] = new Point3D(150, 150, 100);
			points[10] = new Point3D(150, 250, 100);
			points[11] = new Point3D(-150, 250, 100);
			/**
			 * 执行后我们注意到当字母 E 向我们旋转过来时，某些点会变得非常近，并且与第一个3D 例子一样会发生倒置。
			 * 您也许首先会想到增加所有点的 z 值，但这实际上会让效果变得更糟。例如，假设将 z 设为 500。
			 * 旋转的时候，z 将从 500 到 -500，甚至会让有些点运动到观察点更往后的位置，会让事情更糟糕。
			 * 不过我们可以使用 setCenter 方法将所有点向 z 轴推移，如下：
			   for (var i:uint = 0; i < numPoints; i++) {
			   points[i].setVanishingPoint(vpX, vpY);
			   points[i].setCenter(0, 0, 200);
			   }
			   打开 Point3D 类，我们会看到 scale 的计算方法为：
			   var scale:Number = fl / (fl + z + cZ);
			   这样就将整个系统推移了 200 像素，包括旋转系统。原来 z 的值保持不变，只是因为计算透视的值更高了，那么所有物体都将呈现在观察着的前面
			 */
			for (var i:uint = 0; i < numPoints; i++){
				points[i].setVanishingPoint(vpX, vpY);
				points[i].setCenter(0, 0, 200);
			}
			addEventListener(Event.ENTER_FRAME, onEnterFrame);
		}

		private function onEnterFrame(event:Event):void {
			var angleX:Number = (mouseY - vpY) * .001;
			var angleY:Number = (mouseX - vpX) * .001;
			for (var i:uint = 0; i < numPoints; i++){
				var point:Point3D = points[i];
				point.rotateX(angleX);
				point.rotateY(angleY);
			}
			graphics.clear();
			graphics.lineStyle(0);
			graphics.beginFill(0xffcccc);
			graphics.moveTo(points[0].screenX, points[0].screenY);
			for (i = 1; i < numPoints; i++){
				graphics.lineTo(points[i].screenX, points[i].screenY);
			}
			graphics.lineTo(points[0].screenX, points[0].screenY);
			graphics.endFill();
		}
	}

}